<?php
namespace Leran\Controller;
use Common\Controller\DfcommonController;
use Common\Lib\Excel;

class ScoreController extends DfcommonController{
	const MODEL = 'Score';
	/**
	 * 查询条件字段
	 * @var array
	 */
	protected $list_search_field = array('province','city','exam_centre','exam_room','round_id','student','certificate_num','admission_num','phone','unit','subject','exam_status','check','status','level');
	/**
	 * 列表默认显示内容字段
	 * @var array
	 */
	protected $list_show_field =  array('province','city','exam_centre','exam_room','round_id','student','certificate_num','admission_num','phone','unit','subject','exam_status','basis_score','profession_score','total_score','result','sex','education','native','seniority','workingage','region','check','status','ctime','utime','level');
	
	
	public $template = array("index" => 'Score/index',);
	
	public $action = array("upload" => 'uploadScore',);
	
	public $qrCodeRootPath = './data/upload/qrcode/';
	
    public function uploadScore(){
    	
    	$upload = new \Think\Upload();// 实例化上传类
    	$upload->maxSize   =     31457280 ;// 设置附件上传大小
    	$upload->exts      =     array('xls', 'xlsx');// 设置附件上传类型
    	$upload->rootPath  =      './data/upload/'; // 设置附件上传根目录
    	// 上传单个文件
    	$info   =   $upload->uploadOne($_FILES['score']);
    	if(!$info) {// 上传错误提示错误信息
    		$this->error($upload->getError());
    	}else{// 上传成功 获取上传文件信息
    			$config = array(
	    			'filename' => $upload->rootPath.$info['savepath'].$info['savename'],
	    			'fields'=>array('province','city','student','idcard_num','exam_centre','exam_room','round_id','certificate_num','admission_num','phone','subject','exam_status','basis_score','profession_score','total_score',
	    					'result','sex','education','native','seniority','workingage','region','level'),
    			);
    			$check = 2;
    			if(get_current_admin_id() == 1){
    				$check = 1;
    			}
    			$excel = new Excel($config);
    			$data_excel = $excel->import();
    			$data = array();
    			foreach ($data_excel as $item){
    				
    				if($item['province'] == '省' && $item['city'] == '市' && $item['exam_centre'] == '考点名称' && $item['exam_room'] == '考场名称'){
    					continue;
    				}
    				
    				$result = array();
    				foreach ($config['fields'] as $fields){
    					if(!array_key_exists($fields, $item)){
    						$result[$fields] = '';
    					}else{
    						$result[$fields] = $item[$fields];
    					}
    				}
    				
    				$result['importid'] = get_current_admin_id();
    				$result['check'] = $check;
    				$result['status'] = 1;
    				$result['ctime'] = time();
    				$result['utime'] = time();
    				$data[] = $result;
    				
    			}
    			$count = count($data);
    			if($count){
    				$Score = D('Score');
    				$Score->batchInsert($data,null,true);
    				$zipFile = $this->createQrCode($data);
    				$this->success('成功导入<b>'.$count.'</b>条成绩！请等待下载二维码', U('downloadZip?zip='.$zipFile));
    			}else{
    				$this->error('导入失败！请检查Excel文件是否符合格式要求！', U('index'));
    			}
    	}
    }

   
    public function qrCode(){
    	$student = str_replace('请输入考生姓名', '', I('student'));
    	$number = str_replace('请输入准考证号/证件号', '', I('certificate'));//号码
    	if($student == ''){
    		$this->error('考生姓名不能为空！');
    	}
    	if($number == ''){
    		$this->error('准考证号/证件号不能为空！');
    	}
    	Vendor("phpqrcode.phpqrcode");
    	$data = 'http://crehr.com/index.php?g=Portal&m=Index&a=queryQRcode&student='.$student.'&certificate='.$number;
    	// 纠错级别：L、M、Q、H
    	$level = 'L';
    	// 点的大小：1到10,用于手机端4就可以了
    	$size = 4;
    	// 把二维码图片保存到本地,如果要保存图片,用$fileName替换第二个参数false
    	//$fileName = "images/".$size.'.png';
    	
    	\QRcode::png($data, false, $level, $size);
    }
    public function createDownloadQrCode() {
    	
    	$Score = D('Score');
    	$pk = $Score->getPk(); //获取主键名称
    	$ids = I('post.'.$pk);
    	array_filter($ids, 'is_numeric');
    	$where = $pk . " in (" . implode(",", $ids) . ")";
    	$data = $Score->where($where)->select();
    	$zipFileName = $this->createQrCode($data);
    	$this->success('下载二维码', U('downloadZip?zip='.$zipFileName));
    }
    public function downloadXlsx() {
    	$filename =  './data/upload/'.I('xlsx');
    	$this->download($filename);
    }
    public function downloadZip() {
    	$filename = $this->qrCodeRootPath.I('zip');
    	$this->download($filename);
    }
    private function download($filename) {
    	if(!file_exists($filename)){
    		exit("无法找到文件");
    	}
    	header("Cache-Control: public");
    	header("Content-Description: File Transfer");
    	header('Content-disposition: attachment; filename='.basename($filename)); //文件名
    	header("Content-Type: application/zip"); //zip格式的
    	header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
    	header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
    	@readfile($filename);
    }
    private function createQrCode($data) {
    	Vendor("phpqrcode.phpqrcode");
    	$level = 'L';
    	$size = 4;
    	 
    	$dirName = date('YmdHis',time());
    	$filePath = $this->qrCodeRootPath.$dirName;
    	 
    	if(!$this->mkdir($filePath)){
    		return false;
    	}
    	foreach ($data as $item){
    		$admission_num = $item['admission_num'];
    		$student = $item['student'];
    		$idcard = $this->authcode($item['idcard_num'], "ENCODE", "crehr.com");
    		$pngFile = $filePath.'/'.$item['idcard_num'].'.png';
    		$data = 'http://crehr.org/index.php?g=Portal&m=Index&a=queryQRcode&student='.$student.'&certificate='.$admission_num.'&idcard='.$idcard;
    		\QRcode::png($data, $pngFile, $level, $size);
    	}
    	return $this->createZip($dirName);
    }
    private function createZip($zipFileName) {
    	$filePath = $this->qrCodeRootPath.$zipFileName;
    	$zip = new \ZipArchive();
    	if ($zip->open($this->qrCodeRootPath.$zipFileName.'.zip', \ZipArchive::OVERWRITE) === TRUE) {
    		$handler = opendir($filePath);
    		while (($filename = readdir($handler)) !== false) {
    			if ($filename != "." && $filename != "..") {
    				$zip->addFile($filePath . "/" . $filename,$zipFileName.'/'.$filename);
    			}
    		}
    		@closedir($filePath);
    		$zip->close(); //关闭处理的zip文件
    	}
    	return $zipFileName.'.zip';
    }
    /**
     * 创建目录
     * @param  string $savepath 要创建的目录
     * @return boolean          创建状态，true-成功，false-失败
     */
    private function mkdir($dir){
    	if(is_dir($dir)){
    		return true;
    	}
    
    	if(mkdir($dir, 0777, true)){
    		return true;
    	} else {
    		return false;
    	}
    }
    
    /**
     * $string 明文或密文
     * $operation 加密ENCODE或解密DECODE
     * $key 密钥
     * $expiry 密钥有效期
     */
    private function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    	// 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
    	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
    	// 当此值为 0 时，则不产生随机密钥
    	$ckey_length = 4;
    
    	// 密匙
    	// $GLOBALS['discuz_auth_key'] 这里可以根据自己的需要修改
    	$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
    
    	// 密匙a会参与加解密
    	$keya = md5(substr($key, 0, 16));
    	// 密匙b会用来做数据完整性验证
    	$keyb = md5(substr($key, 16, 16));
    	// 密匙c用于变化生成的密文
    	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    	// 参与运算的密匙
    	$cryptkey = $keya.md5($keya.$keyc);
    	$key_length = strlen($cryptkey);
    	// 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
    	// 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    	$string_length = strlen($string);
    	$result = '';
    	$box = range(0, 255);
    	$rndkey = array();
    	// 产生密匙簿
    	for($i = 0; $i <= 255; $i++) {
    		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
    	}
    	// 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上并不会增加密文的强度
    	for($j = $i = 0; $i < 256; $i++) {
    		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
    		$tmp = $box[$i];
    		$box[$i] = $box[$j];
    		$box[$j] = $tmp;
    	}
    	// 核心加解密部分
    	for($a = $j = $i = 0; $i < $string_length; $i++) {
    		$a = ($a + 1) % 256;
    		$j = ($j + $box[$a]) % 256;
    		$tmp = $box[$a];
    		$box[$a] = $box[$j];
    		$box[$j] = $tmp;
    		// 从密匙簿得出密匙进行异或，再转成字符
    		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    	}
    	if($operation == 'DECODE') {
    		// substr($result, 0, 10) == 0 验证数据有效性
    		// substr($result, 0, 10) - time() > 0 验证数据有效性
    		// substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
    		// 验证数据有效性，请看未加密明文的格式
    		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
    			return substr($result, 26);
    		} else {
    			return '';
    		}
    	} else {
    		// 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
    		// 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
    		return $keyc.str_replace('=', '', base64_encode($result));
    	}
    }
    /**
     * 获取添加 修改 显示字段
     * @param string $role 当前用户角色
     * @return array $langs
     */
    protected function _get_field_edit($role='当前用户角色'){
    	$langs = D(static::MODEL)->_getLang();
    	$pk = D(static::MODEL)->_getPk();
    	unset($langs[$pk]);
    	unset($langs['importid']);
    	unset($langs['status']);
    	if(get_current_admin_id() != 1) {
    		unset($langs['check']);
    	}
    	unset($langs['ctime']);
    	unset($langs['utime']);
    	return $langs;
    }
    
    /*
    public function getQrCode() {
    	//     	http://localhost/fjxz/Leran/score/getqrcode
    	 
    	Vendor("phpqrcode.phpqrcode");
    	$level = 'L';
    	$size = 4;
    	 
    	$config = array(
    			'filename' => 'C:/Users/Administrator/Desktop/qrcode_deal/score.xlsx',
    			 
    			'fields'=>array('province','city','student','idcard_num','exam_centre','exam_room','round_id','certificate_num','admission_num','phone','subject','exam_status','basis_score','profession_score','total_score',
    					'result','sex','education','native','seniority','workingage','region'),
    	);
    	 
    	$excel = new Excel($config);
    	$data_excel = $excel->import();
    
    	//$data_excel = array_slice($data_excel, 2040);
    	 
    	foreach ($data_excel as $item){
    		$admission_num = $item['admission_num'];
    		$student = $item['student'];
    		$idcard = $this->authcode($item['idcard_num'], "ENCODE", "crehr.com");
    		$fileName = 'C:/Users/Administrator/Desktop/qrcode_deal/'.$item['idcard_num'].'.png';
    		$data = 'http://crehr.org/index.php?g=Portal&m=Index&a=queryQRcode&student='.$student.'&certificate='.$admission_num.'&idcard='.$idcard;
    		\QRcode::png($data, $fileName, $level, $size);
    	}
    	 
    }
    */
}